X

Js

How to Check if an Object has any Properties

August 24, 2022

/*

Checking if an Object has any Properties


*/

You can use the object.keys(name of object) method to see if the object has any properties in it. If it does, it will return an array with the names of the properties in it. If the object doesn't it will return an empty array.

Checking to see if Object.keys(object) returns a filled array

You can use Object.keys(name of object).length too. If the object has something in it will return a positive number, which is a truthy value. If not it will return 0, a falsey value.

Putting length on Object.keys(object) to return an integer.

/*

Checking for a Property Name


*/

obj.hasOwnProperty(string) test to see if the object has a specific property in it. It returns true if it does, false if it doesn't. The string is the name of the property you want to check for. The obj is the particular object you want to check.

Using obj.hasOwnProperty(string) to check for a property name.

About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.